const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

let firstPoint = null;
let secondPoint = null;
let thirdPoint = null;
let pointArr = [];
let midleArr = [];
canvas.addEventListener("mousedown", (event) => {
  if (!firstPoint) {
    firstPoint = { x: event.offsetX, y: event.offsetY };
  } else if (!secondPoint) {
    secondPoint = { x: event.offsetX, y: event.offsetY };
    drawLine(firstPoint, secondPoint);
  } else if (!thirdPoint) {
    thirdPoint = { x: event.offsetX, y: event.offsetY };
    drawLine(firstPoint, thirdPoint);
    const angle = calculateAngle(firstPoint, secondPoint, thirdPoint);
    displayAngle(angle);
    drawAngleText(angle);
  }
});

function drawLine(start, end) {
  ctx.beginPath();
  ctx.moveTo(start.x, start.y);
  ctx.lineTo(end.x, end.y);
  ctx.stroke();
  const midpoint = {
    x: (start.x * 7 + end.x) / 8,
    y: (start.y * 7 + end.y) / 8,
  };
  pointArr.push(midpoint);
  midleArr.push({
    x: start.x + ((end.x - start.x) * 1) / 4,
    y: start.y + ((end.y - start.y) * 1) / 4,
  });
}

function calculateAngle(first, second, third) {
  const angle1 = Math.atan2(second.y - first.y, second.x - first.x);
  const angle2 = Math.atan2(third.y - first.y, third.x - first.x);
  let angle = angle2 - angle1;
  if (angle > Math.PI) {
    angle -= 2 * Math.PI;
  } else if (angle <= -Math.PI) {
    angle += 2 * Math.PI;
  }
  return (angle * 180) / Math.PI;
}

function displayAngle(angle) {
  const angleDisplay = document.querySelector("#angle-display");
  angleDisplay.textContent = `Angle: ${angle.toFixed(2)} degrees`;
}
function drawArc(pointA, pointB) {
  let midel = {
    x: (midleArr[0].x + midleArr[1].x) / 2,
    y: (midleArr[0].y + midleArr[1].y) / 2,
  };
  ctx.beginPath();
  ctx.moveTo(pointA.x, pointA.y);
  ctx.quadraticCurveTo(midel.x, midel.y, pointB.x, pointB.y);
  ctx.stroke();
}

function drawAngleText(angle) {
  console.log(pointArr);
  drawArc(...pointArr);
  let midela = {
    x: (midleArr[0].x + midleArr[1].x) / 2,
    y: (midleArr[0].y + midleArr[1].y) / 2,
  };
  ctx.font = "10px Arial";
  ctx.fillStyle = "black";
  const angleNum = Math.abs(angle.toFixed(2)) + "°";
  ctx.fillText(angleNum, midela.x, midela.y);
}
